import {useRef, useState} from "react";
import type {DraggableData, DraggableEvent} from "react-draggable";

const useModel = () => {
    const [open, setOpen] = useState(false);
    const [disabled, setDisabled] = useState(true);
    const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
    const draggleRef = useRef<HTMLDivElement>(null);

    const showModal = () => {
        setOpen(true);
    };

    const handleOk = (cb?: () => void) => {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        cb && cb()
        setOpen(false);
    };

    const handleCancel = (cb?: () => void) => {
        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
        cb && cb()
        setOpen(false);
    };

    const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
        const { clientWidth, clientHeight } = window.document.documentElement;
        const targetRect = draggleRef.current?.getBoundingClientRect();
        if (!targetRect) {
            return;
        }
        setBounds({
            left: -targetRect.left + uiData.x,
            right: clientWidth - (targetRect.right - uiData.x),
            top: -targetRect.top + uiData.y,
            bottom: clientHeight - (targetRect.bottom - uiData.y),
        });
    };

    return { open, setOpen, disabled, setDisabled, bounds, draggleRef, showModal, handleOk, handleCancel, onStart }
}

export default useModel